/**
 * @Title: DownloadServlet.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-11-27  yuanchunci
 */
 

package com.ycc.fileTransfer.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.ycc.fileTransfer.entity.FormFile;
import com.ycc.fileTransfer.service.FileTransferService;

/**
 * @ClassName: DownloadServlet
 * @Description: Description of this class
 * @author <a href="mailto:XXX@qq.com">yuanchunci</a>于 2017-11-27 下午3:39:34
 */

public class DownloadServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		ApplicationContext context = new FileSystemXmlApplicationContext( new String []{
				"classpath:spring-mvc.xml",	"classpath:spring-mybatis.xml"});
		FileTransferService fileTransferService = (FileTransferService) context.getBean("FileTransferService");
    	Map param=new HashMap();
		param.put("id", request.getParameter("id"));
		System.out.println(param);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
        // 得到要下载的文件名
		List<FormFile> ls = null;
		try {
			ls = fileTransferService.get(param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(ls.size()==0){
			return ;
		}
		byte[] bb=null;
		// 得到要下载的文件
		 File f=new File(ls.get(0).getFilepath());
         FileInputStream is = new FileInputStream(f);
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         byte[] b = new byte[is.available()];
         int n;
         while ((n = is.read(b)) != -1)
         {
             bos.write(b, 0, n);
         }
         is.close();
         bos.close();
         bb = bos.toByteArray();
		//ls.size()>0?ls.get(0).getContent():null;
		String userAgent = request.getHeader("User-Agent");
		String fileName =ls.get(0).getFilename();// request.getParameter("filename"); // 2323928392489-美人鱼.avi
		byte[] bytes = userAgent.contains("MSIE")?fileName.getBytes():fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
		fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
		response.setHeader("Content-disposition",
		String.format("attachment; filename=\"%s\"", fileName));
		fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
        // 读取要下载的文件，保存到文件输入流
        InputStream fis = new ByteArrayInputStream(bb);
        // 创建输出流
        OutputStream out = response.getOutputStream();
        // 创建缓冲区
        byte buffer[] = new byte[1024];
        int len = 0;
        // 循环将输入流中的内容读取到缓冲区当中
        while ((len = fis.read(buffer)) > 0) {
            // 输出缓冲区的内容到浏览器，实现文件下载
            out.write(buffer, 0, len);
        }
        // 关闭文件输入流
        fis.close();
        // 关闭输出流
        out.close();
    	
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    

}
